package com.googlecode.jch.plugin.runconfiguration;

import com.googlecode.jch.plugin.JCHUtil;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.Location;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.junit.JavaRuntimeConfigurationProducerBase;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;

/**
 * @author Iskander Akishev
 */
public class JCHRunConfigurationProducer extends JavaRuntimeConfigurationProducerBase implements Cloneable {
	private PsiClass solutionClass;

	public JCHRunConfigurationProducer() {
		super(JCHRunConfigurationType.getInstance());
	}

	public PsiElement getSourceElement() {
		return solutionClass;
	}

	@Override
	protected RunnerAndConfigurationSettings createConfigurationByElement(Location location, ConfigurationContext context) {
		location = JavaExecutionUtil.stepIntoSingleClass(location);
		if (location == null) return null;
		final Project project = location.getProject();

		final PsiElement element = location.getPsiElement();
		if (!element.isPhysical()) return null;

		solutionClass = JCHUtil.getSolutionClass(location);
		if (solutionClass == null) return null;

		RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(project, context);
		settings.setName(solutionClass.getName());
		final JCHRunConfiguration configuration = (JCHRunConfiguration)settings.getConfiguration();
		configuration.SOLUTION_CLASS_NAME = solutionClass.getQualifiedName();
		configuration.setName(configuration.getGeneratedName());
		setupConfigurationModule(context, configuration);
		return settings;
	}

	public int compareTo(Object o) {
		return PREFERED;
	}

	@Override
	protected RunnerAndConfigurationSettings findExistingByElement(Location location, @NotNull RunnerAndConfigurationSettings[] existingConfigurations, ConfigurationContext context) {
		final PsiClass solutionClass = JCHUtil.getSolutionClass(location);
		if (solutionClass == null)
			return null;
		for (RunnerAndConfigurationSettings existingConfiguration : existingConfigurations) {
			final JCHRunConfiguration jchRunConfiguration = (JCHRunConfiguration)existingConfiguration.getConfiguration();
			if (Comparing.equal(JavaExecutionUtil.getRuntimeQualifiedName(solutionClass), jchRunConfiguration.SOLUTION_CLASS_NAME) &&
					(Comparing.equal(location.getModule(), jchRunConfiguration.getConfigurationModule().getModule()))
			) {
				return existingConfiguration;
			}
		}
		return null;
	}
}
